﻿//Write a program to convert from any numeral system of given base s to any other numeral system of base d (2 ≤ s, d ≤  16).


using System;
using System.Numerics;

public class FromAnyNumeralSystemToAnyOtherNumeralSystem
{
    public static void Main()
    {
        Console.Write("Enter base of the number range[S >= 2] S = ");
        int baseOfNumber = int.Parse(Console.ReadLine());
        Console.Write("Enter number N = ");
        string userInput = Console.ReadLine();
        int number;
        bool isSuccess = int.TryParse(userInput, out number);
        Console.Write("Enter base to convert the number [D <=16] D = ");
        int divisor = int.Parse(Console.ReadLine());
        char[] array = FillArray(userInput.ToUpper());
        BigInteger integer = ConvertToDecimal(array, baseOfNumber);
        byte[] result = ConvertFromDecimal(integer, divisor);
        Console.Write("Result of the conversion of the number '{0}' is: ", number);
        Print(result);
        Console.WriteLine();
    }

    public static byte[] ConvertFromDecimal(BigInteger number, int divisor)
    {
        int lenght = (number != 0 ? (int)(Math.Log((double)number, divisor) + 1) : 1);
        byte[] array = new byte[lenght];
        for (int i = array.Length - 1; i >= 0; i--)
        {
            array[i] = (byte)(number % divisor);
            number /= divisor;
        }

        return array;
    }

    public static BigInteger ConvertToDecimal(char[] array, int multiplier)
    {
        BigInteger decimalNumber = 0;
        for (int i = 0; i < array.Length; i++)
        {
            BigInteger multiply = 1;
            if ((array[i] - 48) != 0)
            {
                for (int j = 0; j < i; j++)
                {
                    multiply *= multiplier;
                }
            }
            decimalNumber += (array[i] - 48 > 9 ? (array[i] - 55) * multiply : (array[i] - 48) * multiply);
        }

        return decimalNumber;
    }

    private static char[] FillArray(string str)
    {
        char[] array = new char[str.Length];
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = str[array.Length - i - 1];
        }

        return array;
    }

    public static void Print(byte[] array)
    {
        foreach (var item in array)
        {
            if (item > 9)
            {
                Console.Write((char)(item + 55));
            }
            else
            {
                Console.Write(item);
            }
        }
    }
}